package com.atguigu.gulimall.search.controller;

import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.utils.CreatEs;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wjj
 * @create 2023-09-17 14:48
 */
@Controller
public class SearchController {

    @Autowired
    private MallSearchService mallSearchService;

    /**
     * 自动将页面提交过来的所有请求参数封装成我们指定的对象
     * @param param
     * @return
     */
    @GetMapping(value = "/list.html")
    public String listPage(SearchParam param, Model model, HttpServletRequest request,@Value("${elasticsearch.host}") String eUrl,@Value("${gulimall-product.url}") String pUrl) throws Exception {

        param.set_queryString(request.getQueryString());

        //1、根据传递来的页面的查询参数，去es中检索商品
        SearchResult result = null;
        try {
            result = mallSearchService.search(param);
        } catch (Exception e) {

            /** todo
             * 重新导入数据，临时解决搜索数据丢失
             */
            CreatEs creatEs = new CreatEs();
            creatEs.creatEs(eUrl,pUrl);
            result = mallSearchService.search(param);
        }

        model.addAttribute("result",result);

        return "list";
    }
}
